<?php
/** 
* 渠道回调通知
*/
$root = dirname(__FILE__);
$key = 'qddeduction';
require_once $root.'/config.php';
require_once $root.'/mpdo/Db.class.php';
require_once $root.'/mpdo/Log.class.php';
$redis = redis_cluster::getInstance();
$end = time();
$contents = $redis->zrange( $key , 0,$end );
if ($contents) {
	$Log = new Log();
	$dbbdb = new DB('master');
	$timestamp = intval(microtime(true)*1000);
	foreach ($contents as $value) {
		$decode = json_decode($value,1);
		$channel_notify = $dbbdb->row("SELECT * FROM chbc_channel_notify WHERE orderNo = '".$decode['orderNo']."' and type=2 and order_status=".$decode['orderStatus']." order by id desc");
		if ($channel_notify['is_success']==1) {
    		if (!$redis->zremove( $key , $value )) {
    			$redis->zremove( $key , $value );
    		}
			continue; // 防止重复发
		}
		// 验证订单状态更新有没有成功
		$order = $dbbdb->row("SELECT order_status,wm_order_sn FROM chbc_play_order WHERE play_order_no = ".$decode['orderNo']);
		if ($order['order_status']!=$decode['orderStatus']) continue;
		$channel = $dbbdb->row("SELECT * FROM chbc_channel WHERE clientId = '".$decode['clientId']."'");
	    $clientSecret = $channel['clientSecret'];
	    $deductUrl = $channel['deductUrl'];
	    $clientId = $decode['clientId'];
	    $orderNo = $decode['orderNo'];
	    unset($decode['clientId']);
	    unset($decode['orderStatus']);
	    $param['data'] = json_encode($decode);
	    $param['clientId'] = $clientId;
	    $param['timestamp'] = $timestamp;
	    $param['sign'] = sign($param,$clientSecret);
	    $params = json_encode($param);
	    $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
	    $res = curlData($deductUrl,$params,$header);
	    // 成功的情况
	    if ($res) {
	    	$result = json_decode($res,1);
	    	if ($result['code']==200) {
	    		$dbbdb->query('UPDATE chbc_channel_notify SET is_success = 1,times=times+1,update_dt="'.date('Y-m-d H:i:s').'" WHERE id = '.$channel_notify['id']);
	    		if (!$redis->zremove( $key , $value )) {
	    			$redis->zremove( $key , $value );
	    		}
	    		continue;
	    	}
	    }
	    // 失败的情况：如果发送次数不超过3次，隔60s重发
	    if ($channel_notify['times']<3) {
	    	$dbbdb->query('UPDATE chbc_channel_notify SET times=times+1,update_dt="'.date('Y-m-d H:i:s').'" WHERE id = '.$channel_notify['id']);
    		if (!$redis->zremove( $key , $value )) {
    			$redis->zremove( $key , $value );
    		}
    		if ($channel_notify['times']<2) {
			    $score = time()+60;
			    $redis->zadd($key,$score,$value);
    		}
	    }
	}
} else {
	sleep(5);exit;
}
?>
